﻿using IMServer.Models;
using IMServer.Services;

namespace IMServer.Endpoints;

public static class UserAuthEndpoint
{
    public static RouteGroupBuilder MapUserAuthApi(this RouteGroupBuilder group)
    {
        group.MapPost("/register", static async (context) =>
        {
            try
            {
                if (!context.Request.HasFormContentType)
                {
                    await context.Response.WriteAsJsonAsync(new
                    {
                        Code = "1001",
                        Message = "Content type must be multipart/form-data"
                    });
                    return;
                }

                var form = await context.Request.ReadFormAsync();

                // 验证必要字段
                if (string.IsNullOrEmpty(form["UserName"]) || string.IsNullOrEmpty(form["Password"]))
                {
                    await context.Response.WriteAsJsonAsync(new
                    {
                        Code = "1002",
                        Message = "UserName and Password are required"
                    });
                    return;
                }

                var user = new User
                {
                    UserName = form["UserName"].ToString() ?? throw new ArgumentNullException("UserName"),
                    Password = form["Password"].ToString() ?? throw new ArgumentNullException("Password")
                };

                // 处理头像文件
                var avatarFile = form.Files.GetFile("Avatar");
                if (avatarFile != null)
                {
                    // 验证文件类型
                    if (!avatarFile.ContentType.StartsWith("image/"))
                    {
                        await context.Response.WriteAsJsonAsync(new
                        {
                            Code = "1003",
                            Message = "Invalid file type. Only images are allowed."
                        });
                        return;
                    }

                    // 上传到OSS并获取URL
                    string avatarUrl = await OssService.Instance.UploadFileAsync(avatarFile);
                    user.Avatar = avatarUrl;
                }

                // 生成用户ID和密码哈希
                user.GenerateUniqueId();
                user.Password = user.ComputeSha256Hash(user.Password ?? throw new ArgumentNullException("Password"));

                // 保存到数据库
                if (!await UserDbService.Instance.InsertUserAsync(user))
                {
                    await context.Response.WriteAsJsonAsync(new
                    {
                        Code = "5001",
                        Message = "Failed to register user"
                    });
                    return;
                }

                // 创建用户消息箱
                if (!await MessageBoxDbService.Instance.CreateMessageBoxAsync(user.UserId))
                {
                    // 如果消息箱创建失败，记录错误
                    Console.WriteLine($"Failed to create message box for user {user.UserId}");
                    await context.Response.WriteAsJsonAsync(new
                    {
                        Code = "5002",
                        Message = "User registered but failed to create message box"
                    });
                    return;
                }
                
                // 创建待处理消息箱
                if (!await PendingRequestBoxesDbService.Instance.CreatePendingRequestBoxAsync(user.UserId))
                {
                    // 如果消息箱创建失败，记录错误
                    Console.WriteLine($"Failed to create pending request box for user {user.UserId}");
                    await context.Response.WriteAsJsonAsync(new
                    {
                        Code = "5003",
                        Message = "User registered but failed to create pending request box"
                    });
                    return;
                }

                // 返回成功响应
                await context.Response.WriteAsJsonAsync(new
                {
                    Code = "0000",
                    Message = "注册成功!",
                    Data = new
                    {
                        user.UserId,
                        user.UserName,
                        user.Avatar,
                        WebSocketUrl = $"ws://{context.Request.Host}/ws?userId={user.UserId}"
                    }
                });
            }
            catch (Exception ex)
            {
                await context.Response.WriteAsJsonAsync(new
                {
                    Code = "5000",
                    Message = $"Server error: {ex.Message}"
                });
            }
        });

        group.MapPost("/login", async (HttpContext context) =>
        {
            try 
            {
                var loginUser = await context.Request.ReadFromJsonAsync<User>();
                
                if (loginUser == null || 
                    string.IsNullOrEmpty(loginUser.UserId) || 
                    string.IsNullOrEmpty(loginUser.Password))
                {
                    await context.Response.WriteAsJsonAsync(new
                    {
                        Code = "1002",
                        Message = "UserId and Password are required"
                    });
                    return;
                }

                // 从数据库中获取用户信息
                var dbUser = await UserDbService.Instance.GetUserByUserIdAsync(loginUser.UserId);
                
                if (!dbUser.ValidatePassword(loginUser.Password))
                {
                    await context.Response.WriteAsJsonAsync(new
                    {
                        Code = "1005",
                        Message = "Invalid username or password"
                    });
                    return;
                }

                await context.Response.WriteAsJsonAsync(new
                {
                    Code = "0000",
                    Message = "登录成功!",
                    Data = new
                    {
                        dbUser.UserId,
                        dbUser.UserName,
                        dbUser.Avatar,
                        WebSocketUrl = $"ws://{context.Request.Host}/ws?UserId={dbUser.UserId}"
                    }
                });
            }
            catch (Exception ex)
            {
                await context.Response.WriteAsJsonAsync(new
                {
                    Code = "5000",
                    Message = $"Server error: {ex.Message}"
                });
            }
        });

        return group;
    }
}